<?php
class FormValidateError extends CoreException {
	protected $field;
	
	public function __construct($field)
	{
		$this->field = $field;
		$this->library = 'Form';
		$this->type = 'user';
		$this->generalError = false;
		$this->message = $field['label'] . ' ' . $field['error'];
		$this->code = 0;
	}
}

class form {
	protected $fields;
	protected $translate;
	
	public function __construct ($fields = array(), $translate = null)
	{
		$this->fields = $fields;
		$this->translate = $translate;
	}
	
	protected function translate($value)
	{
		if ($this->translate !== null)
		{
			$ret = $this->translate->get($value);
			if ($ret !== null)
			{
				return $ret;
			}
			else
				return $value;
		}
		else
			return $value;
	}
	
	public function addField($field)
	{
		$this->fields[] = $field;
	}
		
	public function Merge($form)
	{
		$this->fields = array_merge($this->fields, $form->fields);
	}
	
	public function Valid($vars)
	{
		foreach ($this->fields as $field)
		{
			if (isset($field['valid']))
			{
				if ($field['valid'] == 'no_null')
				{
					$field['valid'] = '`.`';
					$field['error'] = 'err_null';
				}
				if ($field['valid'] == 'email')
				{
					$field['valid'] = '`[a-z0-9._-]+@[a-z0-9._-]+\\.[a-z]+`i';
					$field['error'] = 'err_mail';
				}
				if (isset($field['error']))
					$field['error'] = $this->translate($field['error']);
				$field['label'] = $this->translate($field['label']);
				if ($field['valid'] == 'callback')
				{
					$ret = call_user_func($field['callback'], $vars[$field['name']]);
					if ($ret !== true)
					{
						$field['error'] = $this->translate($ret);
						throw new FormValidateError($field);
					}
				}
				else
				{
					if (preg_match($field['valid'], $vars[$field['name']]) == 0)
						throw new FormValidateError($field);
				}
			}
		}
		return true;
	}
	
	public function Generate($vals = array())
	{
		$form = '';
		foreach ($this->fields as $field)
		{
			$field['value'] = '';
			if (isset($vals[$field['name']]))
				$field['value'] = $vals[$field['name']];
			if (!isset($field['type']))
				$field['type'] = 'text';
			$form .= $this->MakeField($field);
		}
		return $form;
	}
	
	protected function MakeField($field)
	{
		$label = $this->translate($field['label']);
		return "<p><label>$label<br />"
			."<input type=\"$field[type]\" name=\"$field[name]\" value=\"$field[value]\" />"
			."</label></p>\n";
	}
}